package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constants.RedisConstant;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.springmvc.LeaseException;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void sendCond(String phone) {
        //拼接Key
        String key= RedisConstant.APP_LOGIN_PREFIX+phone;
        //检查是否有这个key
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey){
            //检查手机号是否已经发送过验证码,且有效期还未过时,如果存在,抛出异常发送频繁
            //有效期(总时间):1
            Integer appLoginCodeTtlSec = RedisConstant.APP_LOGIN_CODE_TTL_SEC;
            //间隔时间:2
            Integer appLoginCodeResendTimeSec = RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC;
            //剩余时间:3
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            //总时间-剩余时间<间隔时间,不能发送,发送频繁
            if (appLoginCodeTtlSec-expire <appLoginCodeResendTimeSec){
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        //生成6位数的验证码
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(random.nextInt(10));
        }
        String code = stringBuilder.toString();
        System.out.println("验证码 = " + code);
        //存储到redis中
        redisTemplate.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC,TimeUnit.SECONDS);

    }

    @Override
    public String login(LoginVo loginVo) {
        //根据手机号获取验证码
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        String code = (String) redisTemplate.opsForValue().get(key);
        //如果没有,则代表验证码过期或者没发送
        if (code==null || !code.equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //如果正确,登录或者注册
        LambdaQueryWrapper<UserInfo>userInfoLambdaQueryWrapper=
                new LambdaQueryWrapper<>();
        userInfoLambdaQueryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(userInfoLambdaQueryWrapper);
        //去数据库查询,如果为空,执行注册
        if (userInfo==null){
            //注册
            userInfo=new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            //设置昵称:用户加手机尾号
            userInfo.setNickname("用户"+loginVo.getPhone().substring(7));
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfoService.save(userInfo);
        }
        //判断用户状态是否正常
        if (userInfo.getStatus()==BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //正常状态发令牌
        String token = JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());
        return token;
    }
    @Override
    public UserInfoVo info(String accessToken) {
        //解析
        Integer userId = (Integer) JwtUtil.parseToken(accessToken).get("userId");
        //查询
        UserInfo userInfo = userInfoService.getById(userId);
        //封装
        UserInfoVo userInfoVo = new UserInfoVo(userInfo.getNickname(),userInfo.getAvatarUrl());
        return userInfoVo;
    }
}
